import React, {CSSProperties, useEffect, useMemo, useState} from "react";
import st from './resume-gen.module.css'
import {
    RBasicInformation,
    REduExperience,
    RJobIntent,
    RProjExp,
    RSelfEvaluation,
    RSkills, RTopHeader,
    RWorkExperience
} from "../../components/parts";
import {Button} from "antd";
import {useNavigate, useSearchParams} from "react-router-dom";
import {useAppDispatch, useAppSelector} from "../../redux/hooks";
import {updateResume} from "../../redux/resume-center";
import { message } from "antd";
import { HomeTwoTone } from "@ant-design/icons";
import html2canvas from "html2canvas";
import {getOrder, swapByCompKey} from "../../redux/order";


export const PrintMenu: React.FC = () => {
    const dispatch = useAppDispatch();
    // 路由获取简历id
    const [searchParams, setParams] = useSearchParams()
    const nav = useNavigate();
    const resumeId = searchParams.get('id')
    const [displayBtn, setDisplayBtn] = useState(true)
    const {
        basic, eduExperience, avatar, projectInfoList,
        jobIntent, workInfo, skills, selfEvaluation, resumeCenter, order
    } = useAppSelector(state => state)
    // 简历id 获取当前简历
    const currentResume = resumeCenter.find(d => d.id === resumeId);
    // 消息提示
    const [messageApi, contextHolder] = message.useMessage();


    // 打印前隐藏按钮， 打印后显示
    useEffect(() => {
        const func = ev => { setDisplayBtn(true ); };
        window.addEventListener('afterprint', func)
        return () => {
            window.removeEventListener('afterprint', func)
        }
    }, [])

    let style: CSSProperties = {
        position: "fixed", left: 10, top: 20,
        display: displayBtn ? 'flex' : 'none',
        flexDirection: "column", gap: 14, alignItems: "center"
    }
    return <>
        {contextHolder}
        <div className='option-menu' style={style}>
            <HomeTwoTone style={{fontSize: 40}} onClick={()=> {
                nav('/');
            }} />
            <Button className='no-print'  onClick={() => {
                setDisplayBtn(false)
                Promise.resolve().then(() => {
                    window.print()
                })
            }}>打印</Button>
            <Button  onClick={()=> {
                if (!currentResume) return;
                const toCanvasElement = document.querySelector('#resume-main');
                const canvasWidth = toCanvasElement.clientWidth;
                const canvasHeight = canvasWidth * Math.sqrt(2);
                html2canvas(toCanvasElement as HTMLElement, {
                    width: canvasWidth, height: canvasHeight
                }).then(canvas => {
                    const imgBase64 = canvas.toDataURL('image/jpeg', .1)
                    dispatch(updateResume({
                        ...currentResume, basic, eduExperience, avatar,
                        skills, selfEvaluation, projectInfoList, jobIntent,
                        workInfo, updateDate: +new Date(), imgSrc: imgBase64, order
                    }))
                    messageApi.open({
                        type: 'success',
                        content: '简历保存成功'
                    });
                })
            }}>保存</Button>
        </div>
        {/*<ResumeGen/>*/}
    </>
}

export const ResumeGen: React.FC = () => {
    // const [plist, setPlist] = useState([
    //     { id: 1, compKey: 'basic',},
    //     { id: 2, compKey: 'edu', },
    //     { id: 3, compKey: 'skills', },
    //     { id: 4, compKey: 'jobIntent',},
    //     { id: 5, compKey: 'workExp', },
    //     { id: 6, compKey: 'projectExp', },
    //     { id: 7, compKey: 'selfEvaluation',},
    // ])
    const plist = useAppSelector(getOrder)
    const dispatch = useAppDispatch();

    const compsMap = useMemo(() => ({
        basic: <RBasicInformation/>,
        edu: <REduExperience/>,
        skills: <RSkills/>,
        jobIntent: <RJobIntent/>,
        workExp: <RWorkExperience/>,
        projectExp: <RProjExp/>,
        selfEvaluation: <RSelfEvaluation/>
    }), [])

    const [isDragging, setIsDragging] = useState(false)

    const dragEls = useMemo(() => ({
        drag: document.querySelector('.dragging'),
        noDrag: Array.from(document.querySelectorAll('.drg:not(.dragging)'))
    }), [isDragging])

    function toggleClass(type: 'add' | 'remove') {
        return ( e: React.DragEvent<HTMLDivElement>) => {
            let dragRl = e.currentTarget as HTMLDivElement;
            dragRl.classList[type]('dragging')
            dragRl.classList[type]('limit-height')
            setIsDragging(type === 'add')
        }
    }
    const addDraggingClass = toggleClass('add')
    const removeDraggingClass = toggleClass('remove')

    // function swapByCompKey(dragKey: string | null, hoverKey: string | null) {
        // if (!dragKey || !hoverKey) return;
        // // 触发交换, 根据index交换
        // setPlist(curList => {
        //     const dragItemIdx = curList.findIndex(d => d.compKey === dragKey)
        //     const hoverItemIdx = curList.findIndex(d => d.compKey === hoverKey)
        //     const newList = [...curList]
        //     newList[dragItemIdx] = curList[hoverItemIdx]
        //     newList[hoverItemIdx] = curList[dragItemIdx]
        //     return newList
        // })
    // }

    function containerDragOver(e: React.DragEvent<HTMLDivElement>) {
        e.preventDefault();
        const { drag, noDrag } = dragEls;
        const mousePositionY = e.clientY
        noDrag.forEach((elm) => {
            const {height, top } = elm.getBoundingClientRect();
            // 鼠标到元素中心的位置
            const offset = mousePositionY - top - height / 2
            if (offset < 5 && offset > -5) {
                const compKey = elm.getAttribute('data-id')
                // swapByCompKey(drag?.getAttribute('data-id') || null, compKey)
                dispatch(swapByCompKey({
                  dragKey: drag?.getAttribute('data-id') || null,
                    hoverKey: compKey
                }))
            }
        })
    }

    return <div>
        <PrintMenu/>
        <div id='resume-main' className={st['resume-main']}>
            <RTopHeader />
            <div
                onDragOver={containerDragOver}
                style={{  margin: '0 36px', }}>
                {
                    plist.map((c, index) => (
                        <div
                            data-id={c.compKey}
                            onDragStart={addDraggingClass}
                            onDragEnd={removeDraggingClass}
                            key={c.compKey} className='drg' draggable>
                            {
                                // @ts-ignore
                                compsMap[c.compKey]
                            }
                        </div>
                    ))
                }
            </div>
        </div>
    </div>
}
